goog.provide('td.Grid');

goog.require('Stefan.Rect');
goog.require('Stefan.fill.Border');
goog.require('td.Weapon');
goog.require('td.Army');

td.Grid = T.lang.createClass(function(config) {
	Stefan.Rect.call(this, config);
    this.config = config || {};
    this.map = config.map;
	this.pX = config.x;
	this.pY = config.y;
	this.width = config.width || 50;
	this.height = config.height || 50;
	this.isEntrance = config.isEntrance || false;
	this.color = config.color;
	this.defaultColor = this.color;
	this.isExit = config.isExit || false;
	this.passable = config.passable === undefined?true:config.passable;
	this.building = null;
	this.canBuild = config.canBuild === undefined?true:config.canBuild;
	this.init();
}, {
	superClass: Stefan.Rect
}).extend({
	init: function () {
		this.setSize(this.width, this.height).setPosition(this.pX, this.pY).setFill(this.color).setBorder(
			new Stefan.fill.Border({
				width: 1,
				color: 'rgba(255,0,0,.1)'
			})).setAnchor(.5, .5);
	},
	addWeapon: function (weapon) {
		this.appendChild(weapon.body);
		this.building = weapon;
	},
	onOver: function() {
		if (this.map.type == 'main' && td.GAME.getSelectMap().selectedWeapon) {
			var mask = td.Weapon.getMask(td.GAME.getSelectMap().selectedWeapon);
			if (!this.building && this.canBuild) {
				mask.hide(false) ;
				mask.setPosition(this.pX, this.pY);
			} else {
				mask.hide(true) ;
			}
		}
	},
	build: function(type){
		var cost = td.Weapon.getCfg(type).cost || 0;
		// if (td.MONEY >= cost) {
			// td.MONEY -= cost;
			var weapon = this.building = new td.Weapon({type: type, grid: this});
			this.appendChild(weapon.body);
			td.Weapon.getMask(type).hide(true);
		// }
	},
	onClick: function() {
		if (td.GAME.controller.selectMap.selectedWeapon && this.map.type == 'main' && !this.building && this.canBuild) {
			if (!this.map.ifBlock(this)) {
				this.build(td.GAME.getSelectMap().selectedWeapon);
			}
		}
		else {
			if(this.building && !td.GAME.controller.selectMap.selectedWeapon) {
		    	if(this.map.selectWeapon) {
		    		var grid = this.map.selectWeapon.grid;
		    		grid.setFill(grid.defaultColor);
		    	}
				this.setFill('rgba(255,0,0,.4)');
				this.map.selectWeapon = this.building;
			}
		}
	},
	addArmy: function(arr) {
		for(var i = 0, maxi = arr.length; i < maxi; i++){
			var army = new td.Army({type: arr[i], grid: this}).setPosition(td.GRIDSIZE/2, td.GRIDSIZE/2);
			this.map.armyArr.push(army);
			army.index = this.map.armyArr.length - 1;
			this.map.appendChild(army);
		}
	}
});
